<?php


namespace App\Utility;


use EasySwoole\Component\Process\AbstractProcess;
use EasySwoole\Component\Process\Config;
use EasySwoole\Component\Singleton;
use EasySwoole\EasySwoole\ServerManager;
use Swoole\Process;

class ProcessManager
{
    use Singleton;

    private $processList = [];

    /**
     * @param string $processName
     * @param string $processClass
     * @param array $args
     * @return Process|null
     */
    public function setProcess(string $processClass, array $args = [], ?string $processName = ''): ?Process
    {
        $processConfig = new Config();
        if (!$processName) {
            $processName = $processClass;
        }

        $processConfig->setProcessName($processName);

        $processConfig->setArg($args);

        if (ServerManager::getInstance()->isStart()) {
            trigger_error("you can not add a process {$processName}.{$processClass} after server start");
            return null;
        }

        $key = md5($processName);
        if (isset($this->processList[$key])) {
            trigger_error("you can not add the same name process : {$processName}.{$processClass}");
            return null;
        }

        $process = new $processClass($processConfig);
        if ($process instanceof AbstractProcess) {
            $swooleProcess = $process->getProcess();
            $this->processList[$key] = $swooleProcess;

            $server = ServerManager::getInstance()->getSwooleServer();
            $server->addProcess($swooleProcess);
        } else {
            trigger_error("Object does not inherit AbstractProcess process : {$processName}.{$processClass}");
            return null;
        }

        return $this->processList[$key];
    }

    /**
     * @param string $processName
     * @return Process|null
     */
    public function getProcess(string $processName): ?Process
    {
        $key = md5($processName);
        if (isset($this->processList[$key])) {
            return $this->processList[$key];
        } else {
            return null;
        }
    }
}